#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

/*
	system()会调用fork()产生子进程，由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令，
	
	此命>令执行完后随即返回原调用的进程。在调用system()期间SIGCHLD 信号会被暂时搁置，SIGINT和SIGQUIT 信号则会被忽略。
	
	返回值

	=-1 : 出现错误 
	= 0 : 调用成功但是没有出现子进程 
	> 0 : 成功退出的子进程的id
 */

int main(int argc, char ** argv)
{
  int c;
  const char * opts;
  char time[32];
  char cmd[64];
  char * ymd;
  char * hms;
  int ret;

  if (argc < 2) {
    printf("usage : %s {-t [year-mount-day_hh:mm:ss] | -s [command] }\n", argv[0]);
    exit(0);
  }

  ret = system("df -h > /tmp/df.txt");
  printf("system return is : %d\n", ret);

  opts = "t:hs:";
  while ( (c = getopt (argc, argv, opts)) != -1 ) {
    switch (c) {
    case 't':
      memset(time, 0, sizeof(time));
      strcpy(time, optarg);      
      printf("time = %s\n", time);

      ymd = strtok(time, "_");
      hms = strtok(NULL, "_");

      memset(cmd, 0, sizeof(cmd));
      sprintf(cmd, "date -s \"%s %s\"", ymd, hms);
      printf("cmd = %s\n", cmd);

      ret = system(cmd);  /* success is 0, and fial is 256. please more than test. */
      printf("system return is : %d\n", ret);
      break;

    case 's':
      ret = system(optarg);
      printf("system return is : %d\n", ret);
      break;

    default:
      break;
    }
  }
  

  return 0;
}
